﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace MacIPChecker.Services;

public class IPAddressService
{
    /// <summary>
    /// 获取所有活跃网络接口的IP地址（排除环回地址）
    /// </summary>
    public Dictionary<string, List<string>> GetActiveIPAddresses()
    {
        var result = new Dictionary<string, List<string>>();

        try
        {
            // 获取所有网络接口
            foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces())
            {
                // 过滤条件：接口已启用、非环回、类型为以太网或无线
                if (networkInterface.OperationalStatus == OperationalStatus.Up &&
                    !networkInterface.NetworkInterfaceType.ToString().Contains("Loopback") &&
                    (networkInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
                     networkInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211))
                {
                    var ipAddresses = new List<string>();

                    // 获取接口关联的IP地址
                    foreach (var unicastAddress in networkInterface.GetIPProperties().UnicastAddresses)
                    {
                        // 排除环回地址，区分IPv4和IPv6
                        if (!IPAddress.IsLoopback(unicastAddress.Address))
                        {
                            string ipInfo = unicastAddress.Address.AddressFamily == AddressFamily.InterNetwork
                                ? $"IPv4: {unicastAddress.Address}"
                                : $"IPv6: {unicastAddress.Address}";
                            ipAddresses.Add(ipInfo);
                        }
                    }

                    if (ipAddresses.Any())
                    {
                        result.Add(networkInterface.Name, ipAddresses);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            result.Add("错误", new List<string> { $"获取IP失败：{ex.Message}" });
        }

        return result;
    }
}